package com.intelligentmeterreadingsys.waterbanding.activity;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.StrictMode;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.intelligentmeterreadingsys.R;
import com.intelligentmeterreadingsys.httpserver.HttpClientServer;
import com.intelligentmeterreadingsys.httpserver.RequestUrl;
import com.intelligentmeterreadingsys.povo.WaterInfoVO;
import com.intelligentmeterreadingsys.util.SharedPreferenceUtil;
import com.intelligentmeterreadingsys.util.TipHelper;
import com.intelligentmeterreadingsys.waterbanding.db.WaterBandingImpl;

import dbhelper.XmlNameHelper;

/**
 * 一键上传水表绑定信息
 * 
 * @author king
 * 
 */
public class WaterBandingUploadActivity extends Activity {

    public Button button;// 上传按钮

    public TextView textview1;// 需上传总数

    public TextView textview2;// 未上传总数

    public TextView textview3;// 进度条描述

    public ProgressBar pb;// 进度条

    public WaterBandingImpl dao;

    public List<WaterInfoVO> list;

    public RequestUrl r;
    public boolean b = true;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

	super.onCreate(savedInstanceState);
	StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder().detectDiskReads().detectDiskWrites().detectNetwork().penaltyLog().build());
	StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder().detectLeakedSqlLiteObjects().detectLeakedSqlLiteObjects().penaltyLog().penaltyDeath().build());
	setContentView(R.layout.waterbanding_onetoupload);
	r = new RequestUrl(this);
	init();
    }

    /**
     * 初始化控件
     */
    public void init() {
	b = true;
	button = (Button) findViewById(R.id.waterbanding_upload_button);
	pb = (ProgressBar) findViewById(R.id.waterbanding_progressBar);
	textview1 = (TextView) findViewById(R.id.waterbanding_upload_total);
	textview2 = (TextView) findViewById(R.id.waterbanding_noupload_total);
	textview3 = (TextView) findViewById(R.id.waterbanding_pb_textview);
	dao = new WaterBandingImpl(this);
	textview1.setText(dao.queryBandingTotal() + "");
	textview2.setText(dao.queryBandingNoUpload() + "");

	button.setOnClickListener(new OnClickListener() {

	    @Override
	    public void onClick(View v) {
		if (b) {
		    list = dao.queryNoUpload();
		    if (list == null || list.size() < 1) {
			Toast.makeText(WaterBandingUploadActivity.this, "没有可上传的数据!", Toast.LENGTH_SHORT).show();
			return;
		    }
		    pb.setMax(list.size());
		    textview3.setText("正在上传中0%");
		    MyHandler.post(runnable);
		} else {
		    Toast.makeText(WaterBandingUploadActivity.this, "正在上传中!", Toast.LENGTH_SHORT).show();
		    return;
		}
	    }
	});

    }

    @Override
    protected void onDestroy() {
	dao.close();
	super.onDestroy();
    }

    Handler MyHandler = new Handler() {

	@Override
	public void handleMessage(Message msg) {

	    if (msg.what == 1) {

		textview3.setText("正在上传中" + ((float) (msg.arg1 + 1) / list.size()) * 100 + "%");
		pb.setProgress(msg.what);
		if (msg.arg1 == list.size() - 1) {

		    Map<String, String> map = new HashMap<String, String>();
		    for (int i = 0; i < list.size(); i++) {
			map.put(list.get(i).getWaternumber(), "1");
			textview3.setText("100%");
			pb.setProgress(list.size());
		    }
		    boolean b = dao.ModifyUploadStatus(map);
		    MyHandler.removeCallbacks(runnable);

		    textview1.setText(dao.queryBandingTotal() + "");
		    textview2.setText(dao.queryBandingNoUpload() + "");
		    dao.close();
		    b = true;
		    Toast.makeText(WaterBandingUploadActivity.this, "上传成功", Toast.LENGTH_LONG).show();
		    TipHelper.Vibrate(WaterBandingUploadActivity.this, 1000);

		}
	    } else if (msg.what == 2) {
		b = true;
		MyHandler.removeCallbacks(runnable);
		textview3.setText("上传失败");
		TipHelper.Vibrate(WaterBandingUploadActivity.this, 1000);

		Toast.makeText(WaterBandingUploadActivity.this, "上传失败，请检查网络", Toast.LENGTH_LONG).show();
	    }
	}

    };

    Runnable runnable = new Runnable() {

	@Override
	public void run() {
	    b = false;
	    SharedPreferenceUtil sh = new SharedPreferenceUtil(WaterBandingUploadActivity.this);
	    String id = sh.getValue(XmlNameHelper.IMSI);

	    for (int i = 0; i < list.size(); i++) {
		Map<String, String> map = new HashMap<String, String>();
		map.put("waternumber", list.get(i).getWaternumber());
		map.put("latitude", list.get(i).getLatitude() + "");
		map.put("longitude", list.get(i).getLongitude() + "");
		map.put("RFIDnumber", list.get(i).getRFIDnumber());
		map.put("addr", list.get(i).getAdds());
		map.put("imsi", id);
		HttpClientServer server = new HttpClientServer(WaterBandingUploadActivity.this);

		String response = server.doPost(map, RequestUrl.BandingWater);
		System.out.println(response + "----------------");
		if (response.equals("error")) {
		    Message msgs = MyHandler.obtainMessage();
		    msgs.what = 2;
		    MyHandler.sendMessage(msgs);
		} else {
		    try {
			JSONObject json = new JSONObject(response);
			String message = json.getString("message");
			if (message.equals("yes")) {
			    Message msgs = MyHandler.obtainMessage();
			    msgs.what = 1;
			    msgs.arg1 = i;
			    MyHandler.sendMessage(msgs);
			} else {
			    Message msgs = MyHandler.obtainMessage();
			    msgs.what = 2;
			    MyHandler.sendMessage(msgs);
			}
		    } catch (JSONException e) {
			Message msgs = MyHandler.obtainMessage();
			msgs.what = 2;
			MyHandler.sendMessage(msgs);
		    }

		}
	    }
	}
    };

}
